import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import styles from "./popup.module.less";

function Popup() {
  const [cookies, setCookies] = useState([]);
  const [localStorageItems, setLocalStorageItems] = useState([]);
  const [sessionStorageItems, setSessionStorageItems] = useState([]);

  const [update, setUpdate] = useState({});

  useEffect(() => {
    // document.addEventListener("DOMContentLoaded", function () {
    // 发送消息给content script，请求当前网站的存储信息
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      const tab0 = tabs[0];
      const url = new URL(tab0.url);
      chrome.cookies.getAll({ domain: url.origin }).then((result) => {
        console.log(reulst);
      });

      chrome.tabs.sendMessage(tabs[0].id, { action: "getAllStorage" }, function (response) {
        // 处理收到的存储信息
        if (response) {
          // displayStorage("cookieList", response.cookies);
          // displayStorage("localStorageList", response.localStorage);
          // displayStorage("sessionStorageList", response.sessionStorage);
          setCookies(response.cookies);
          setLocalStorageItems(response.localStorage);
          setSessionStorageItems(response.sessionStorage);
        }
      });
    });
    // });

    try {
      chrome.cookies.getAll({ domain }).then((result) => {
        console.log(reulst);
      });

      // if (cookies.length === 0) {
      //   return 'No cookies found';
      // }

      // let pending = cookies.map(deleteCookie);
      // await Promise.all(pending);

      // cookiesDeleted = pending.length;
    } catch (error) {
      return `Unexpected error: ${error.message}`;
    }
  }, [update]);

  const sendAction = (action) => {
    // 发送消息给content script，请求删除存储信息
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      // { action: "deleteStorage", key: item }
      chrome.tabs.sendMessage(tabs[0].id, action);

      // 刷新数据
      setUpdate({});
    });
  };

  //   chrome.cookies.getAll({ url: "https://www.example.com/" }, function(cookies) {
  //   for (var i = 0; i < cookies.length; i++) {
  //     chrome.cookies.remove({
  //       url: "https://www.example.com/",
  //       name: cookies[i].name
  //     });
  //   }
  // });

  return (
    <div className={styles.popup}>
      <div className={styles.lineTitle}>
        Cookies<button onClick={() => sendAction({ action: "clearCookie", key: item.key })}>清空</button>
      </div>
      <ul className={styles.list}>
        {cookies.map((item) => (
          <li className={styles.listItem}>
            <div className={styles.title}>{item}</div>
            <button className={styles.delBtn} onClick={() => sendAction({ action: "deleteCookie", key: item })}>
              删除
            </button>
          </li>
        ))}
      </ul>

      <div className={styles.lineTitle}>
        Local Storage<button onClick={() => sendAction({ action: "clearLocalStorage" })}>清空</button>
      </div>
      <ul className={styles.list}>
        {localStorageItems.map((item) => (
          <li className={styles.listItem}>
            <div className={styles.title}>{`${item.key}:${item.value}`}</div>
            <button
              className={styles.delBtn}
              onClick={() => sendAction({ action: "deleteLocalStorage", key: item.key })}
            >
              删除
            </button>
          </li>
        ))}
      </ul>

      <div className={styles.lineTitle}>
        Session Storage<button onClick={() => sendAction({ action: "clearSessionStorage" })}>清空</button>
      </div>
      <ul className={styles.list}>
        {sessionStorageItems.map((item) => (
          <li className={styles.listItem}>
            <div className={styles.title}>{`${item.key}:${item.value}`}</div>
            <button
              className={styles.delBtn}
              onClick={() => sendAction({ action: "deleteSessionStorage", key: item.key })}
            >
              删除
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<Popup />);
